<template>
  <ElDialog v-model="dialogVisible" :title="`修改密码${username ? ' - ' + username : ''}`" width="30%" align-center>
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <ElFormItem label="旧密码" prop="old_password">
        <ElInput v-model="formData.old_password" type="password" placeholder="请输入旧密码" />
      </ElFormItem>
      <ElFormItem label="新密码" prop="new_password">
        <ElInput v-model="formData.new_password" type="password" placeholder="请输入新密码(至少6位)" />
      </ElFormItem>
      <ElFormItem label="确认新密码" prop="confirm_password">
        <ElInput v-model="formData.confirm_password" type="password" placeholder="请再次输入新密码" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { changeUserPassword } from '@/api/system/user'
import { HttpError } from '@/utils/http/error'

interface Props {
  visible: boolean
  userId?: number
  username?: string
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const username = computed(() => props.username || '')

const formRef = ref<FormInstance>()
const formData = reactive({
  old_password: '',
  new_password: '',
  confirm_password: ''
})

const rules: FormRules = {
  old_password: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '新密码至少6位', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (value !== formData.new_password) {
          callback(new Error('两次输入的新密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      Object.assign(formData, { old_password: '', new_password: '', confirm_password: '' })
      nextTick(() => formRef.value?.clearValidate())
    }
  }
)

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return
    const id = props.userId
    if (!id) {
      ElMessage.error('缺少用户ID，无法修改密码')
      return
    }

    try {
      await changeUserPassword(id, {
        old_password: formData.old_password,
        new_password: formData.new_password
      })
      dialogVisible.value = false
      emit('submit')
    } catch (err) {
      console.error('修改密码失败', err)
      if (!(err instanceof HttpError)) {
        ElMessage.error('修改密码失败，请稍后重试')
      }
    }
  })
}
</script>

<style scoped></style>